<template>
  <div class="config-page app-container">
    <div class="head" v-loading='listLoading'>
      <div class="chunk title">
        <div class="product">
          <h3>{{info.compositionName}}</h3>
          <p class="tips">
          </p>
        </div>
        <div class="fromLine">
          <div class="label">名义金额：</div>
          <div class="fromLine-content">{{info.nominalAmount}} 万元</div>
        </div>
        <div style="font-size: 13px;" class="info">
          <div class="fromLine">
            <div class="label">投资金额：</div>
            <div class="fromLine-content" style="min-width: 100px;">{{info.initMoney}} 万元</div>
            <div class="label">固收金额(年化)：</div>
            <div class="fromLine-content"><el-input-number style="width: 80px;" v-model="info.fixedIncome" size="mini" :controls="false"></el-input-number> %</div>
          </div>
          <div class="fromLine">
            <div class="label">已占用金额：</div>
            <div class="fromLine-content">{{typeof compositionUseMonry == 'number' ? compositionUseMonry : ''}} 万元</div>
          </div>
        </div>
        <div style="font-size: 13px;" class="info2">
          <div>
            <div class="fromLine">
              <div class="label">开始日期：</div>
              <div class="fromLine-content">
                <el-date-picker
                  v-model="info.createdTime"
                  size="mini"
                  type="date"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                  style="width: 140px;height: 24px;"
                  placeholder="开始时间">
                </el-date-picker>
              </div>
            </div>
            <div class="fromLine">
              <div class="label">备注：</div>
              <div class="fromLine-content">{{info.mark}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="card" v-loading='listLoading'>
      <div class="content">
        <div class="list1-card" v-for="(items, i) in list1" :key="i">
          <div class="card-content card1-content">
            <div class="short">分类{{i+1}}</div>
            <div><span class="label">分类名称</span> <el-input :class="{'border_red': ruleList[i]&&ruleList[i].classfy[0]}" size="mini" v-model="items.classfyName" style="width: 160px;"></el-input></div>
            <div class="width20" style="padding-left: 15px;"><span>名义金额：</span> <span>{{items.nominalAmount}} 万元</span></div>
            <div style="padding-left: 15px;"><span class="label">投资金额</span> <el-input-number :class="{'border_red': ruleList[i]&&ruleList[i].classfy[1]}" size="mini" v-model="items.initMoney" @change="classfyCurrentMoneyHandle(i)" :controls="false" style="width: 120px;"></el-input-number> 万元</div>
            <!-- <div style="padding-left: 15px;"><span>已占用金额：</span> <span>{{classfyUseMoneyHandle(items)}} 万元</span></div> -->
            <div style="padding-left: 15px;"><span>已占用金额：</span> <span>{{items.occuped}} 万元</span></div>
            <div style="max-width: 250px;"><span class="label">对标指数</span> <indexSelectTree :class="{'border_red': ruleList[i]&&ruleList[i].classfy[2]}" :multiple="false" size="mini" :width="120" v-model="items.indexType"></indexSelectTree></div>
            <div class="iconGrounp short">
              <el-tooltip v-if="list1.length>1" effect="dark" content="删除分类" placement="top">
                <i class="el-icon-close icon" @click="delectClassfyHandle(i)"></i>
              </el-tooltip>
              <el-tooltip effect="dark" content="添加策略" placement="top">
                <i class="el-icon-circle-plus icon" @click="addStrategyHandle(i)"></i>
              </el-tooltip>
              <el-tooltip v-if="i==list1.length-1" effect="dark" content="添加分类" placement="top">
                <i class="el-icon-plus icon" @click="addClassfyHandle"></i>
              </el-tooltip>
            </div>
          </div>
          <div class="list2-card" v-for="(item, index) in items.classifyStrategyExt" :key="index">
            <div class="card-content card2-content">
              <div class="short">策略{{index+1}}</div>
              <div><span class="label">策略名称</span>
                <el-input :class="{'border_red': ruleList[i]&&ruleList[i].strategy[index][0]}" size="mini" v-model="item.strategyName" placeholder="请选择策略" clearable readonly style="width: 215px;">
                  <el-button slot="append" icon="el-icon-search" @click="selectStrategyHandle(i, index)"></el-button>
                </el-input>
              </div>
              <div style="padding-left: 15px;"><span class="label">投资金额</span> <el-input-number :class="{'border_red': ruleList[i]&&ruleList[i].strategy[index][1]}" size="mini" v-model="item.currentMoney" @change="currentMoneyHandle(i, index)" :controls="false" style="width: 120px;"></el-input-number> 万元</div>
              <div class="width25" style="padding-left: 15px;"><span class="label">杠杆率</span> <el-input-number size="mini" v-model="item.leverageRatio" @change="leverageRatioChange($event, i, index)" :precision="2" :controls="false" :min="1" style="width: 80px;"></el-input-number></div>
              <div style="padding-left: 15px;"><span>开始时间：</span>
                <el-date-picker
                 :class="{'border_red': ruleList[i]&&ruleList[i].strategy[index][2]}"
                  v-model="item.enterTime"
                  size="mini"
                  type="date"
                  @change="enterTimeChange($event, i, index)"
                  value-format="yyyy-MM-dd"
                  style="width: 140px;"
                  placeholder="请选择开始时间">
                </el-date-picker>
              </div>
              <!-- <div style="max-width: 250px;"></div> -->
              <div class="iconGrounp">
                <el-tooltip v-if="items.classifyStrategyExt.length>1" effect="dark" content="删除策略" placement="top">
                  <i class="el-icon-remove icon" @click="delectStrategyHandle(i, index)"></i>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="footer">
      <el-button type="primary" size="small" @click="saveHandle(1)">预览</el-button>
      <el-button type="primary" size="small" @click="saveHandle(2)">保存</el-button>
    </div>

    <strategyOpen v-if="strategyVisible" ref="strategyOpen" :userId="userId" @selctInvestName="selctInvestNameHandle"></strategyOpen>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getCompositionAndClassifysByCompositionId, configComposition } from '@/api/combManage'
import indexSelectTree from '@/components/investComn/indexSelectTree.vue'
import strategyOpen from '@/views/afterManage/afterInvest/relation/strategyOpen.vue'
import { parseTime } from '@/utils'

export default {
  name: 'StrategyCombManageConfig',
  components: { strategyOpen, indexSelectTree },
  data() {
    return {
      strategyVisible: false,
      strategy_i: undefined,
      strategy_index: undefined,
      compositionUseMonry: 0,

      compositionId: '',
      listLoading: false,
      info: {},
      list1: [],

      ruleList: []
    }
  },
  created() {
    this.compositionId = this.$route.query.compositionId
    this.getInfo()
  },
  activated() {
    if(this.compositionId != this.$route.query.compositionId) {
      this.compositionId = this.$route.query.compositionId
      this.getInfo()
    }
  },
  computed: {
    ...mapGetters(['userId']),
  },
  methods: {
    enterTimeChange(date, i, index) {
      if(new Date(date) <= new Date(this.info.createdTime)) {
        this.info.createdTime = date
      }else {
        let res_date = ''
        this.list1.map(items => {
          items.classifyStrategyExt.map(item => {
            if(!res_date) {
              res_date = item.enterTime
            }else if(new Date(item.enterTime) < new Date(res_date)) {
              res_date = item.enterTime
            }
          })
        })
        this.info.createdTime = res_date
      }
    },
    classfyCurrentMoneyHandle(i) {
      let n = 0
      this.list1.map(item => {
        n += item.initMoney
      })
      if(n>this.info.initMoney) {
        this.$nextTick(() => {
          // this.list1[i].initMoney = this.info.initMoney - (n - this.list1[i].initMoney)
          this.list1[i].initMoney = undefined
          this.$message({
            message: '分类总投资金额不能超过该组合投资金额',
            type: 'warning',
          })
        })
      }
      let m = 0
      this.list1[i].classifyStrategyExt.map(item => {
        m += item.currentMoney
      })
      if(this.list1[i].initMoney<m) {
        this.$nextTick(() => {
          // this.list1[i].initMoney = m
          this.list1[i].initMoney = undefined
          this.$message({
            message: '分类投资金额不能小于该分类下策略总投资金额',
            type: 'warning',
          })
        })
      }
    },
    leverageRatioChange(val, i, index) {
      if(val==undefined) { // 本身为1时不能识别刷新
        this.list1[i].classifyStrategyExt[index].leverageRatio = 1
      }
      
      let all_nominalAmount = 0
      this.list1[i].classifyStrategyExt.map(item => {
        all_nominalAmount += (item.currentMoney * item.leverageRatio)
      })
      if(all_nominalAmount>0) this.list1[i].nominalAmount = all_nominalAmount

      let info_all_nominalAmount = 0
      this.list1.map(item => {
        info_all_nominalAmount += item.nominalAmount
      })
      this.info.nominalAmount = info_all_nominalAmount
    },
    currentMoneyHandle(i, index) {
      let n = 0
      let all_nominalAmount = 0
      this.list1[i].classifyStrategyExt.map(item => {
        n += item.currentMoney
        all_nominalAmount += (item.currentMoney * item.leverageRatio)
      })
      if(n>this.list1[i].initMoney) {
        this.$nextTick(() => {
          this.list1[i].classifyStrategyExt[index].currentMoney = undefined
          this.$message({
            message: '策略总投资金额不能超过该分类投资金额',
            type: 'warning',
          })
        })
      }
      if(all_nominalAmount>0) this.list1[i].nominalAmount = all_nominalAmount
      this.list1[i].classifyStrategyExt[index].initialMoney = this.list1[i].classifyStrategyExt[index].currentMoney

      let info_all_nominalAmount = 0
      this.list1.map(item => {
        info_all_nominalAmount += item.nominalAmount
      })
      this.info.nominalAmount = info_all_nominalAmount

      this.classfyUseMoneyHandle(i)
    },
    addClassfyHandle() {
      this.list1.push({
        createdBy: this.userId,
        compositionId: this.compositionId,
        classfyName: '',
        nominalAmount: undefined,
        initMoney: undefined,
        classifyStrategyExt: [],
        indexType: undefined,
        createdTime: parseTime(new Date())
      })
    }, 
    delectClassfyHandle(i) {
      this.$confirm(`确认删除分类名称【${this.list1[i].classfyName}】此条数据？`, '提示', {
        type: 'warning'
      }).then(_ => {
        this.list1.splice(i, 1)
      }).catch(_ => {})
    }, 
    addStrategyHandle(i) {
      this.list1[i].classifyStrategyExt.push({
        leverageRatio: 1,
        createdBy: this.userId,
        updatedBy: this.userId, // todo
        strategyName: '',
        currentMoney: undefined,
        initMoney: undefined,
        createdTime: new Date(),
        updatedTime: new Date(),
        enterTime: new Date()
      })
    }, 
    delectStrategyHandle(i, index) {
      this.$confirm(`确认删除策略名称【${this.list1[i].classifyStrategyExt[index].strategyName}】此条数据？`, '提示', {
        type: 'warning'
      }).then(_ => {
        this.list1[i].classifyStrategyExt.splice(index, 1)
        
        let res_date = ''
        this.list1.map(items => {
          items.classifyStrategyExt.map(item => {
            if(!res_date) {
              res_date = item.enterTime
            }else if(new Date(item.enterTime) < new Date(res_date)) {
              res_date = item.enterTime
            }
          })
        })
        this.info.createdTime = res_date
      }).catch(_ => {})
    },
    selctInvestNameHandle(strategyInfoVo) {
      this.list1[this.strategy_i].classifyStrategyExt[this.strategy_index].strategyId = strategyInfoVo.strategyId
      this.list1[this.strategy_i].classifyStrategyExt[this.strategy_index].strategyName = strategyInfoVo.strategyName
      this.list1[this.strategy_i].classifyStrategyExt[this.strategy_index].enterTime = strategyInfoVo.makeTime
      if(new Date(strategyInfoVo.makeTime) < new Date(this.info.createdTime)) this.info.createdTime = strategyInfoVo.makeTime
    },
    selectStrategyHandle(i, index) {
      this.strategy_i = i
      this.strategy_index = index
      this.strategyVisible = true
      this.$nextTick(() => {
        this.$refs.strategyOpen.init()
      })
    },
    classfyUseMoneyHandle(i) {
      const res = 0
      if(!this.list1[i].classifyStrategyExt.length) {
        return res
      }
      this.list1[i].occuped = 0
      this.list1[i].classifyStrategyExt.map(item => {
        if(item.currentMoney) {
          this.list1[i].occuped += item.currentMoney
        }
      })
      this.compositionUseMonry = 0
      this.list1.map(item => {
        this.compositionUseMonry += (item.occuped?item.occuped:0)  // 策略占用
      })
    },
    getInfo() {
      this.listLoading = true
      getCompositionAndClassifysByCompositionId({
        compositionId: this.compositionId
      }).then(res => {
        this.listLoading = false
        this.list1 = res.body.strategyClassifyVo
        this.info = res.body.strategyCompositionVo
        this.list1.map((item, i) => {  // 分类占用
          this.classfyUseMoneyHandle(i)
        })
      })
    },
    saveHandle(goDetailPage) {
      // 校验
      let check = true
      let noEmpty = false
      this.ruleList = []
      for (let i=0; i<this.list1.length; i++) {
        const obj = this.list1[i]
        if(obj.classfyName == this.info.compositionName) {
          this.$message({
            message: '分类名称不能和组合名称相同',
            type: 'warning'
          })
          check = false
          return
        }
        if(!obj.classifyStrategyExt.length) {
          this.$message({
            message: '分类下至少存在一条策略',
            type: 'warning'
          })
          check = false
          return
        }
        if(!this.ruleList[i]) {
          this.ruleList[i] = {
            classfy: [false,false,false],
            strategy: []
          }
        }
        if(!obj.classfyName) {
          this.$set(this.ruleList[i].classfy, 0, true)
          noEmpty = true
        }
        if(!obj.initMoney) {
          this.$set(this.ruleList[i].classfy, 1, true)
          noEmpty = true
        }
        if(!obj.indexType) {
          this.$set(this.ruleList[i].classfy, 2, true)
          noEmpty = true
        }
        for (let j=0; j<obj.classifyStrategyExt.length; j++) {
          this.ruleList[i].strategy[j] = [false,false,false]
          const o = obj.classifyStrategyExt[j]
          if(!o.strategyName) {
            this.$set(this.ruleList[i].strategy[j], 0, true)
            noEmpty = true
          }
          if(!o.currentMoney) {
            this.$set(this.ruleList[i].strategy[j], 1, true)
            noEmpty = true
          }
          if(!o.enterTime) {
            this.$set(this.ruleList[i].strategy[j], 2, true)
            noEmpty = true
          }
        }
      }
      if(!check) return 
      if(noEmpty) {
        this.$message({
          message: '存在未填项',
          type: 'warning'
        })
        return 
      }

      configComposition({
        strategyCompositionVo: { 
          compositionId: this.info.compositionId, createdTime: this.info.createdTime,
          nominalAmount: this.info.nominalAmount, initMoney: this.info.initMoney,
          fixedIncome: this.info.fixedIncome
        },
        strategyClassifyVo: this.list1
      }).then(res => {
        if(res.code == 0) {
          if(goDetailPage == 1) {
            this.$notify({
              message: res.body,
              type: 'success',
              duration: 2000
            })
            this.$router.push({
              path: `/strategyComb/combManage/netWorthAnalysis/${this.compositionId}`
            })
          }else if(goDetailPage == 2) {
            this.$notify({
              message: res.body,
              type: 'success',
              duration: 2000
            })
            this.$store.dispatch("tagsView/delView", this.$route)
            this.$router.push('/strategyComb/combManage')
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.config-page {
  .card {
    min-height: 80px;
    margin-top: 60px;
    padding: 15px;
    border: 1px solid #ddd;
    overflow-x: auto;
    .content {
      min-width: 1300px;
    }
    .list1-card {
      margin-top: 10px;
    }
    .list2-card {
      margin-top: 10px;
    }
    .card-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 6px 10px;
      div { width: 30%; }
      .short { width: 80px; }
      .width25 { width: 25%; }
      .width20 { width: 20%; }
      // .name-money {width: 25%;}
      // .leverageRatio {width: 25%;}
      .label {
        padding-right: 10px;;
      }
      .iconGrounp {
        width: 150px;
        .icon {
          font-size: 18px;
          font-weight: bold;
          cursor: pointer;
          & + .icon { margin-left: 10px; }
        }
        .el-icon-close,.el-icon-remove {
          font-size: 20px;
          color: red;
        }
        .el-icon-plus,.el-icon-circle-plus {
          font-size: 20px;
          color: #0af;
        }
      }
    }
    .card1-content {
      background: rgb(220, 237, 255);
    }
    .card2-content {
      border: 1px solid #eee;
      border-radius: 4px;
    }
  }
  .footer {
    margin-top: 60px;
    text-align: right;
    padding-right: 40px;
    ::v-deep .el-button {
      width: 160px;
      height: 40px;
    }
  }

  .head {
    padding: 15px 15px 0;
    border: 1px solid #e1e0e0;
    font-size: 14px;
    .redFont { color: #c00; }
    .fromLine {
      display: flex;
      line-height: 29px;
      .label { width: 100px; text-align: right; }
    }
    .chunk {
      display: flex;
      > div:nth-of-type(1) { width: 16%; }
      > div:nth-of-type(2) { width: 20%; }
      > div:nth-of-type(3) { width: 44%; }
      > div:nth-of-type(4) { width: 25%; }
      .chunk-strategyType { 
        width: 100% !important; height: 100%;
        display: flex;
        > div { flex: 1; }
        > div + div {
          border-left: 1px dashed #e1e0e0;
          margin-left: 20px;
        }
        .netWorth-strategyType {
          justify-content: space-around;
        }
      }
      .history-strategyType {
        div {
          display: flex;align-items: center;
          .label {
            justify-content: flex-end;
          }
        }
        & + .history-strategyType {
          margin-left: 20px;
        }
      }
    }
    .chunk + .chunk { border-top: 1px dashed #e1e0e0; }
    .title {
      height: 64px;
      .product {
        h3 {font-size: 22px;}
        .tips {
          margin-top: 30px;
          .tip {
            border: 1px solid #3D71AE;
            color: #3D71AE;
            padding: 3px 6px;
            & + .tip { margin-left: 6px; }
          }
        }
      }
    }
  }
}
</style>

